/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Mobilottery.UI.Forms;

import Mobilottery.Interfaces.IAlertCommandListener;
import Mobilottery.AppManager;
import Mobilottery.Constants.Consts;
import Mobilottery.Constants.Consts.Screens;
import Mobilottery.Interfaces.IBackgroundOperation;
import Mobilottery.Utils.UtilsConnection;
import Mobilottery.XmlManager;
import Mobilottery.XmlManager.LoginDetails;
import javax.microedition.lcdui.*;

/**
 *
 * @author WindowsVista
 */
public class FormLogin extends Form implements CommandListener
{

    private TextField _tfUserName;
    private TextField _tfPassword;

    public FormLogin()
    {
        super("Login screen");

        ImageItem img = new ImageItem(
                null,
                Consts.UIConsts.IMAGES_LOGO,
                Item.LAYOUT_VCENTER | Item.LAYOUT_CENTER | Item.LAYOUT_NEWLINE_AFTER,
                "MOBILottery",
                Item.PLAIN);
        this.append(img);

        _tfUserName = new TextField("UserName", "", 10, TextField.ANY);
        _tfUserName.setLayout(Item.LAYOUT_TOP | Item.LAYOUT_LEFT);
        this.append(_tfUserName);

        _tfPassword = new TextField("Password", "", 10, TextField.PASSWORD);
        this.append(_tfPassword);

        Command cmd;
        cmd = new Command("Login", Command.OK, 0);
        this.addCommand(cmd);

        cmd = new Command("Exit", Command.EXIT, 0);
        this.addCommand(cmd);

        this.setCommandListener(this);
    }

    public void commandAction(Command c, Displayable d)
    {
        String cmdLabelName = c.getLabel().toLowerCase();
        if (cmdLabelName.equals("login") == true)
        {
            login_Clicked();
        }
        else if (cmdLabelName.equals("exit") == true)
        {
            exit_Clicked();
        }
    }

    private void exit_Clicked()
    {
        AppManager.setAlert(
                "Exit Mobilottery",
                "Are you sure you want to close application?",
                AlertType.CONFIRMATION,
                new IAlertCommandListener()
                {

                    public boolean onOK()
                    {
                        AppManager.closeApplication();
                        return false;
                    }

                    public boolean onCancel()
                    {
                        return true;
                    }
                });
    }

    private void login_Clicked()
    {
        final String username = _tfUserName.getString().trim();
        final String password = _tfPassword.getString();

        if (username.equals("") || password.equals(""))
        {
            // data is missing...
            AppManager.setAlert(
                    "Login",
                    "Username or Password are missing!",
                    AlertType.INFO,
                    "Continue", null,
                    new IAlertCommandListener()
                    {

                        public boolean onOK()
                        {
                            // return to current screen
                            return true;
                        }

                        public boolean onCancel()
                        {
                            // return to current screen
                            return true;
                        }
                    });

            // exit method
            return;
        }
        else
        {
            AppManager.runBackgroundOperation(
                    "Log in...",
                    "Checking credentials...",
                    new IBackgroundOperation()
                    {

                        public boolean execute()
                        {
                            System.out.println("LoginForm   |   conncetion for login | Start ");
                            // Create request xml
                            String requestUrl =
                                    Consts.Urls.Login +
                                    "&userid=" + username +
                                    "&pass=" + password;
                            String recvXml = UtilsConnection.GetData(requestUrl);

                            System.out.println("LoginForm   |   conncetion for login | end ");

                            // for testing...................
                            //recvXml = "<root><status>0</status><status_desc>This is error message....</status_desc></root>";
                            //recvXml = "<root><status>1</status><status_desc>OK</status_desc><login_date>01/01/2007 10:34</login_date></root>";

                            System.out.println("LoginForm   |   parse login xml | begin");

                            LoginDetails loginDetails = XmlManager.ProcessXml_Login(recvXml);

                            System.out.println("LoginForm   |   parse login xml | end");
                            if (loginDetails.loginSuccessfuly() == true)
                            {
                                // authenticated

                                /*
                                final StringBuffer sbMsg = new StringBuffer();
                                sbMsg.append("Logged in ");
                                sbMsg.append(loginDetails.LoginDate);
                                sbMsg.append("!");

                                if (loginDetails.RecentlyFinishedGames != null &&
                                loginDetails.RecentlyFinishedGames.length() > 0)
                                {
                                sbMsg.append("\r\nThe following games have been recently updatesd:");
                                String[] strs = DataHelper.Split(",", loginDetails.RecentlyFinishedGames);
                                for (int i = 0; i < strs.length; i++)
                                {
                                sbMsg.append("\r\n - ");
                                sbMsg.append(strs[i]);
                                }
                                }

                                System.out.println("FormLogin   |   message created");

                                
                                Timer t = new Timer();
                                t.schedule(new TimerTask()
                                {

                                public void run()
                                {
                                AppManager.setAlert(
                                "Login",
                                sbMsg.toString(),
                                AlertType.INFO,
                                "Continue",
                                null,
                                new IAlertCommandListener()
                                {

                                public boolean onOK()
                                {
                                AppManager.goToScreen(Screens.MainMenu, null);

                                // manualy switching screen, so don't need to return to previos screen
                                return false;
                                }

                                public boolean onCancel()
                                {
                                // not getting here (not cancel button)
                                return true;
                                }
                                });
                                }
                                }, 500);
                                 * */

                                // store login details
                                AppManager.Username = username;
                                AppManager.Password = password;

                                // goto main menu
                                AppManager.goToScreen(Screens.MainMenu, loginDetails);

                                // manualy switching screen, so don't need to return to previos screen
                                return false;
                            }
                            else
                            {
                                System.out.println("LoginForm   |   show error message");

                                // data is missing...
                                AppManager.setAlert(
                                        "Login",
                                        "Username or Password are missing!",
                                        AlertType.INFO,
                                        "Continue", null,
                                        new IAlertCommandListener()
                                        {

                                            public boolean onOK()
                                            {
                                                // return to current screen
                                                return true;
                                            }

                                            public boolean onCancel()
                                            {
                                                // return to current screen
                                                return true;
                                            }
                                        });


                                System.out.println("LoginForm   |   will return to prev screen");

                                // not switching screen, so back to previos screen
                                return false;
                            }
                        }
                    });
        }
    }
}
